package com.swt.mto.thithu.portlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.PortletException;
import javax.portlet.ResourceRequest;
import javax.portlet.ResourceResponse;

import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.json.JSONFactoryUtil;
import com.liferay.portal.kernel.json.JSONObject;
import com.liferay.portal.kernel.util.WebKeys;
import com.liferay.portal.theme.ThemeDisplay;
import com.liferay.util.bridges.mvc.MVCPortlet;
import com.swt.mto.thithu.model.Answer;
import com.swt.mto.thithu.model.LoadAjax;
import com.swt.mto.thithu.model.Question;
import com.swt.mto.thithu.model.Quiz;
import com.swt.mto.thithu.model.QuizCategory;
import com.swt.mto.thithu.service.AnswerLocalServiceUtil;
import com.swt.mto.thithu.service.LoadAjaxLocalServiceUtil;
import com.swt.mto.thithu.service.QuestionLocalServiceUtil;
import com.swt.mto.thithu.service.QuizCategoryLocalServiceUtil;
import com.swt.mto.thithu.service.QuizLocalServiceUtil;

/**
 * Portlet implementation class QuanLyCauHoiPortlet
 */
public class QuanLyCauHoiPortlet extends MVCPortlet {

	public void serveResource(ResourceRequest resourceRequest,
			ResourceResponse resourceResponse) throws PortletException,
			IOException {
		ThemeDisplay themeDisplay = (ThemeDisplay) resourceRequest
				.getAttribute(WebKeys.THEME_DISPLAY);
		if (resourceRequest.getResourceID().equals("new-question-catalogy")) {
		
			QuizCategory quizCategory = null;
			String strParentId = resourceRequest.getParameter("parentId");
			Long parentId=null;
			if(strParentId == null){
				parentId = (long) 0;
			}else{
				strParentId = strParentId.replace("c", "");
				parentId = Long.parseLong(strParentId);
			}
			try {
				quizCategory = QuizCategoryLocalServiceUtil
						.addQuizCategory(null, themeDisplay.getUserId(), null, parentId, "New Category");
			} catch (PortalException e) {
				e.printStackTrace();
			} catch (SystemException e) {
				e.printStackTrace();
			}
			
			String str ="c"+ quizCategory.getParentId()+ "!@#<li rel = 'folder' id='c"+ quizCategory.getQuizCategoryId() +"' class='jstree-closed jstree-last c"+quizCategory.getParentId()+"'>"; 
			str+=			"<ins class='jstree-icon'>&nbsp;</ins>";
			str+=			"<a href='javascript:;' class='jstree-clicked'><ins class='jstree-icon'>&nbsp;</ins>" + quizCategory.getTitle() + "</a>";
			str+=		"</li>!@#c"+quizCategory.getQuizCategoryId();
			resourceResponse.setContentType("text/html; charset=UTF-8");

			PrintWriter writer = resourceResponse.getWriter();
			writer.write(str);
					
		}
		
		if (resourceRequest.getResourceID().equals("load")){
			
			LoadAjax loadAjax;
			try {
				loadAjax = LoadAjaxLocalServiceUtil.fetchLoadAjax(1);
					
				resourceResponse.setContentType("text/html; charset=UTF-8");
				PrintWriter writer = resourceResponse.getWriter();
				writer.write(loadAjax.getLoadWeb());
			} catch (SystemException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		if (resourceRequest.getResourceID().equals("saveTree")){
			LoadAjax loadAjax;
			try {
				loadAjax = LoadAjaxLocalServiceUtil.fetchLoadAjax(1);
				String path = resourceRequest.getParameter("saveTreePara");
				loadAjax.setLoadWeb(path);
				LoadAjaxLocalServiceUtil.updateLoadAjax(loadAjax);
			} catch (SystemException e) {
				e.printStackTrace();
			}
		}
		
		if (resourceRequest.getResourceID().equals("update-quiz-catalogy")){
			QuizCategory quizCategory = null;
			String strQuizCategoryId = resourceRequest.getParameter("quizCategoryId");
			String title = resourceRequest.getParameter("title");
			Long quizCategoryId=null;
			if(strQuizCategoryId == null){
				quizCategoryId = (long) 0;
			}else{
				strQuizCategoryId = strQuizCategoryId.replace("c", "");
				quizCategoryId = Long.parseLong(strQuizCategoryId);
			}
			try {
				Long createUserId = QuizCategoryLocalServiceUtil.fetchQuizCategory(quizCategoryId).getCreateUserId();
				Long parentId = QuizCategoryLocalServiceUtil.fetchQuizCategory(quizCategoryId).getParentId();
				quizCategory = QuizCategoryLocalServiceUtil
						.addQuizCategory(quizCategoryId, createUserId, themeDisplay.getUserId(), parentId, title);
			} catch (PortalException e) {
				e.printStackTrace();
			} catch (SystemException e) {
				e.printStackTrace();
			}
			
			resourceResponse.setContentType("application/json; charset=UTF-8");
			JSONObject json = JSONFactoryUtil.createJSONObject();
			json.put("id", quizCategory.getQuizCategoryId());
			json.put("title",quizCategory.getTitle());
			resourceResponse.getWriter().write(json.toString());
		}
		
		if (resourceRequest.getResourceID().equals("remove-quiz-catalogy")){
			String strQuizCategoryId = resourceRequest.getParameter("quizCategoryId");
			strQuizCategoryId = strQuizCategoryId.replace("c", "");
			Long quizCategoryId = Long.parseLong(strQuizCategoryId);
			try {
				QuizCategoryLocalServiceUtil.deleteQuizCategory(quizCategoryId);
				
			} catch (PortalException e) {
				e.printStackTrace();
			} catch (SystemException e) {
				e.printStackTrace();
			}
			
			
			
			resourceResponse.setContentType("application/json; charset=UTF-8");
			JSONObject json = JSONFactoryUtil.createJSONObject();
			json.put("id", resourceRequest.getParameter("quizCategoryId"));
			resourceResponse.getWriter().write(json.toString());
		}
		
		if (resourceRequest.getResourceID().equals("new-quiz")) {
			
			Quiz quiz = null;
			String strQuizCategoryId = resourceRequest.getParameter("parentId");
			Long QuizCategoryId=null;
			if(strQuizCategoryId == null){
				QuizCategoryId = (long) 0;
			}else{
				strQuizCategoryId = strQuizCategoryId.replace("c", "");
				QuizCategoryId = Long.parseLong(strQuizCategoryId);
			}
			try {
				quiz = QuizLocalServiceUtil
						.addQuiz(null, themeDisplay.getUserId(), null, QuizCategoryId, "New Quiz", 0,"");
			} catch (PortalException e) {
				e.printStackTrace();
			} catch (SystemException e) {
				e.printStackTrace();
			}
			
			String str ="c"+ quiz.getQuizCategoryId()+ "!@#<li rel = 'quiz' id='b"+ quiz.getQuizId() +"' class='jstree-closed jstree-last c"+quiz.getQuizCategoryId()+"'>"; 
			str+=			"<ins class='jstree-icon'>&nbsp;</ins>";
			str+=			"<a href='javascript:;' class='jstree-clicked'><ins class='jstree-icon'>&nbsp;</ins>" + quiz.getTitle() + "</a>";
			str+=			"<input type='hidden' value='" + quiz.getTime() + "' />";
			str+=			"<input type='hidden' value='" + quiz.getDescription() + "' />";
			str+=		"</li>!@#b"+quiz.getQuizId();
			resourceResponse.setContentType("text/html; charset=UTF-8");

			PrintWriter writer = resourceResponse.getWriter();
			writer.write(str);		
		}
		
		if (resourceRequest.getResourceID().equals("update-quiz")){
			Quiz quiz = null;
			String strQuizId = resourceRequest.getParameter("quizId");
			String title = resourceRequest.getParameter("title");
			Long quizId=null;
			if(strQuizId == null){
				quizId = (long) 0;
			}else{
				strQuizId = strQuizId.replace("b", "");
				quizId = Long.parseLong(strQuizId);
			}
			
			int time = Integer.parseInt(resourceRequest.getParameter("time"));
			String description = resourceRequest.getParameter("description");
			
			try {
				Long createUserId = QuizLocalServiceUtil.fetchQuiz(quizId).getCreateUserId();
				Long quizCategoryId = QuizLocalServiceUtil.fetchQuiz(quizId).getQuizCategoryId();
				quiz = QuizLocalServiceUtil
						.addQuiz(quizId, createUserId, themeDisplay.getUserId(), quizCategoryId, title, time, description);
			} catch (PortalException e) {
				e.printStackTrace();
			} catch (SystemException e) {
				e.printStackTrace();
			}
			
			resourceResponse.setContentType("application/json; charset=UTF-8");
			JSONObject json = JSONFactoryUtil.createJSONObject();
			json.put("id", quiz.getQuizId());
			json.put("title",quiz.getTitle());
			json.put("test","yes");
			json.put("time",quiz.getTime());
			json.put("description",quiz.getDescription());
			resourceResponse.getWriter().write(json.toString());
		}
		
		
		if (resourceRequest.getResourceID().equals("remove-quiz")){
			String strQuizId = resourceRequest.getParameter("quizId");
			strQuizId = strQuizId.replace("b", "");
			Long quizId = Long.parseLong(strQuizId);
			try {
				QuizLocalServiceUtil.deleteQuiz(quizId);
				
			} catch (PortalException e) {
				e.printStackTrace();
			} catch (SystemException e) {
				e.printStackTrace();
			}
			
			
			
			resourceResponse.setContentType("application/json; charset=UTF-8");
			JSONObject json = JSONFactoryUtil.createJSONObject();
			json.put("id", resourceRequest.getParameter("quizId"));
			json.put("test", "yes");
			resourceResponse.getWriter().write(json.toString());
		}
		
		if (resourceRequest.getResourceID().equals("new-question")) {
			
			Question question = null;
			String strQuizId = resourceRequest.getParameter("parentId");
			Long quizId=null;
			if(strQuizId == null){
				quizId = (long) 0;
			}else{
				strQuizId = strQuizId.replace("b", "");
				quizId = Long.parseLong(strQuizId);
			}
			try {
				question = QuestionLocalServiceUtil
						.addQuestion(null, themeDisplay.getUserId(), null, quizId, "New Question", "");
			} catch (PortalException e) {
				e.printStackTrace();
			} catch (SystemException e) {
				e.printStackTrace();
			}
			
			String str ="b"+ question.getQuizId()+ "!@#<li rel = 'entity' id='q"+ question.getQuestionId() +"' class='jstree-leaf jstree-last b"+question.getQuizId()+"'>"; 
			str+=			"<ins class='jstree-icon'>&nbsp;</ins>";
			str+=			"<a href='javascript:;' class='jstree-clicked'><ins class='jstree-icon'>&nbsp;</ins>" + question.getTitle() + "</a>";
			str+=			"<input type='hidden' value='" + question.getDescription() + "' />";
			str+=		"</li>!@#q"+question.getQuestionId();
			resourceResponse.setContentType("text/html; charset=UTF-8");

			PrintWriter writer = resourceResponse.getWriter();
			writer.write(str);		
		}
		
		
		if (resourceRequest.getResourceID().equals("remove-question")){
			String strQuestionId = resourceRequest.getParameter("questionId");
			strQuestionId = strQuestionId.replace("q", "");
			Long questionId = Long.parseLong(strQuestionId);
			try {
				QuestionLocalServiceUtil.deleteQuestion(questionId);
				
			} catch (PortalException e) {
				e.printStackTrace();
			} catch (SystemException e) {
				e.printStackTrace();
			}
			
			
			
			resourceResponse.setContentType("application/json; charset=UTF-8");
			JSONObject json = JSONFactoryUtil.createJSONObject();
			json.put("id", resourceRequest.getParameter("questionId"));
			json.put("test", "yes");
			json.put("entry", "question");
			resourceResponse.getWriter().write(json.toString());
		}
		
		if (resourceRequest.getResourceID().equals("update-question")){
			Question question = null;
			String strQuestionId = resourceRequest.getParameter("questionId");
			String title = resourceRequest.getParameter("title");
			String strAnswer = resourceRequest.getParameter("answer");
			String[] answerStrings = strAnswer.split("\\.");
			
			String strAnswerPosition = resourceRequest.getParameter("answerPosition");
			String[] answerStringPostions = strAnswerPosition.split("\\.");
			
			int answerType = Integer.parseInt(resourceRequest.getParameter("answerType"));
			
			Long questionId=null;
			if(strQuestionId == null){
				questionId = (long) 0;
			}else{
				strQuestionId = strQuestionId.replace("q", "");
				questionId = Long.parseLong(strQuestionId);
			}
			
			List<Answer> answers =  AnswerLocalServiceUtil.getAnswerByQuestion(questionId);
			for(Answer answer : answers){
				boolean flag = false;
				for(int i=0; i<answerStrings.length; i++){
					 long answerId = Long.parseLong(answerStrings[i].replace("view", ""));
					 if (answer.getAnswerId() == answerId){
						 flag = true;
					 } 
				}
				if(flag == false){
					try {
						AnswerLocalServiceUtil.deleteAnswer(answer);
					} catch (SystemException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
			String description = resourceRequest.getParameter("description");
			
			try {
				Long createUserId = QuestionLocalServiceUtil.fetchQuestion(questionId).getCreateUserId();
				Long quizId = QuestionLocalServiceUtil.fetchQuestion(questionId).getQuizId();
				question = QuestionLocalServiceUtil
						.addQuestion(questionId, createUserId, themeDisplay.getUserId(), quizId, title, description);
			} catch (PortalException e) {
				e.printStackTrace();
			} catch (SystemException e) {
				e.printStackTrace();
			}
			//process answer
			if(strAnswer != ""){
				for(int i=0; i<answerStrings.length; i++){
					 long answerId = Long.parseLong(answerStrings[i].replace("view", ""));
					 int answerPosition = Integer.parseInt(answerStringPostions[i]);
					 try {
						 AnswerLocalServiceUtil.addAnswer(answerId, themeDisplay.getUserId(),themeDisplay.getUserId(), questionId, answerType, description, "1", answerPosition);
						 //AnswerLocalServiceUtil.addAnswer(answer);
					 } catch (SystemException e) {
						 // TODO Auto-generated catch block
						 e.printStackTrace();
					 } catch (PortalException e) {
						 // TODO Auto-generated catch block
						 e.printStackTrace();
					 }
				}
				try {
					LoadAjax ajax = LoadAjaxLocalServiceUtil.fetchLoadAjax(1);
					ajax.setPrimaryAnswer(Long.parseLong(answerStrings[answerStrings.length-1].replace("view", ""))+1);
					LoadAjaxLocalServiceUtil.updateLoadAjax(ajax);
				} catch (SystemException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			 
			
			resourceResponse.setContentType("application/json; charset=UTF-8");
			JSONObject json = JSONFactoryUtil.createJSONObject();
			json.put("id", question.getQuestionId());
			json.put("title",question.getTitle());
			json.put("test","yes");
			json.put("entry","question");
			json.put("description",question.getDescription());
			String temp="";
			if(strAnswer != ""){
				for(int i=0; i<answerStrings.length; i++){
					temp+= "<input type='hidden' value= ''>";
				}
				json.put("html",temp);
			}else{
				json.put("html", "");
			}
			resourceResponse.getWriter().write(json.toString());
		}
		
		if (resourceRequest.getResourceID().equals("getAnswerId")){
			long answerId=0;
			try {
				answerId = LoadAjaxLocalServiceUtil.fetchLoadAjax(1).getPrimaryAnswer();
			} catch (SystemException e) {
				e.printStackTrace();
			}
			resourceResponse.setContentType("application/json; charset=UTF-8");
			JSONObject json = JSONFactoryUtil.createJSONObject();
			json.put("id", String.valueOf(answerId));
			resourceResponse.getWriter().write(json.toString());
		}
		
		if (resourceRequest.getResourceID().equals("getListAnswer")){
			long questionId = Long.parseLong(resourceRequest.getParameter("questionId"));
			List<Answer> answers = AnswerLocalServiceUtil.getAnswerByQuestion(questionId);
			resourceResponse.setContentType("application/json; charset=UTF-8");
			JSONObject json = JSONFactoryUtil.createJSONObject();
			String answerIds ="";
			for(Answer answer:answers){
				answerIds+=answer.getAnswerId() +".";
			}
			System.out.println(answerIds);
			json.put("answerIds",answerIds);
			resourceResponse.getWriter().write(json.toString());
		}
	}
	
	public void createQuestion(ActionRequest actionRequest, ActionResponse actionResponse)
			throws PortletException, IOException {
		 String editor = actionRequest.getParameter("htmlCodeFromEditorPlacedHere");
		 
		 actionResponse.setRenderParameter("editor", editor);
		 actionResponse.setRenderParameter("jspPage", "/html/quanlycauhoi/view.jsp");
		 sendRedirect(actionRequest, actionResponse);
		 System.out.println(editor);
	}
	
	public void redirectAdd(ActionRequest actionRequest, ActionResponse actionResponse)
			throws PortletException, IOException {
		System.out.println("hihi");
		actionResponse.setRenderParameter("jspPage", "/html/quanlycauhoi/createQuestion.jsp");
		sendRedirect(actionRequest, actionResponse);
	}
}
